// Copyright 2013 Ronald Schlenker, www.technewlogic.de.
// 
// This file is part of Byond.
// 
// Byond is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// Byond is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Byond.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using Autofac.Core;
using Module = Autofac.Module;

namespace Utils.Messaging
{
	public class MessageInterceptionModule : Module
	{
		protected override void AttachToComponentRegistration(
			IComponentRegistry componentRegistry,
			IComponentRegistration registration)
		{
			registration.Activating += (s, e) => ActivateMessaging(e.Instance);
		}

		private readonly List<WeakReference> _instances = new List<WeakReference>();

		private void ActivateMessaging(object instance)
		{
			ActivateHandleMessage(instance);
			ActivateSendMessage(instance);
		}

		private void ActivateHandleMessage(object instance)
		{
			lock (_instances)
				_instances.Add(new WeakReference(instance));
		}

		private void ActivateSendMessage(object instance)
		{
			instance
				.GetAllEvents()
				.Where(it => it.EventHandlerType == typeof(MessageEventHandler))
				.ForEach(it =>
					it.AddEventHandler(instance, new MessageEventHandler(message =>
						DispatchMessage(message, instance))));
		}

		private void DispatchMessage(object message, object sender)
		{
			List<object> potentialMessageReceiver;
			lock (_instances)
			{
				potentialMessageReceiver = _instances
					.Select(it => it.Target)
					.Where(it => it != null)
					.ToList();
			}

			// IMP: Ganz unten kommt es ab und zu zu einer STA Thread Exception (beim Invoke).
			// Mit SyncContext und synchron gibt es aber DeadLocks...
			potentialMessageReceiver.ForEach(it =>
				it.GetType()
					.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
					.Where(it2 => it2.Name == "HandleMessage")
					.Where(it2 => it2.ReturnType == typeof(void))
					.Where(it2 => it2.GetParameters().Length == 1)
					.Where(it2 => it2.GetParameters().First().ParameterType == message.GetType())
					.ForEach(it2 => it2.Invoke(it, new[] { message })));
		}
	}
}
